package com.ruoyi.excel.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.JsonUtils;
import com.ruoyi.excel.domain.AsyncImportExportTask;
import com.ruoyi.excel.domain.bo.AsyncImportExportTaskBo;
import com.ruoyi.excel.domain.vo.AsyncImportExportTaskVo;
import com.ruoyi.excel.mapper.AsyncImportExportTaskMapper;
import com.ruoyi.excel.service.IAsyncImportExportTaskService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;

import java.util.*;

import static com.ruoyi.common.helper.LoginHelper.getUserId;

@Service
public class AsyncImportExportTaskService extends ServiceImpl<AsyncImportExportTaskMapper, AsyncImportExportTask> implements IAsyncImportExportTaskService {
    @Autowired
    AsyncImportExportTaskMapper baseMapper;

    @Override
    public List<AsyncImportExportTask> getTaskAndUpdateStatusSynchronized() {
        // 查询状态为 init 的任务
        List<AsyncImportExportTask> list = baseMapper.selectByTimeAndStatus(DateUtil.date(), 1);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<Long> taskIds = new ArrayList<>();
        //收集任务id
        list.forEach(asyncImportExportTask -> {
            taskIds.add(asyncImportExportTask.getTaskId());
        });
        UpdateWrapper<AsyncImportExportTask> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("task_status", 2);
        updateWrapper.set("deal_time", new Date());
        updateWrapper.in("task_id", taskIds);
        baseMapper.update(null, updateWrapper);
        return list;
    }

    /**
     * 查询异步excel任务中心列表
     */
    @Override
    public TableDataInfo<AsyncImportExportTaskVo> queryPageList(AsyncImportExportTaskBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<AsyncImportExportTask> lqw = buildQueryWrapper(bo);
        Page<AsyncImportExportTaskVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    @Autowired
    private ISysUserService sysUserService;
    @Override
    public Boolean addExport(List listData,Class javaType,String sheetName) {
        AsyncImportExportTask asyncImportExportTask = new AsyncImportExportTask();
        asyncImportExportTask.setCreatedTime(new Date());
        asyncImportExportTask.setTaskCode("D-A-01");
        asyncImportExportTask.setTaskName("导出"+sheetName);

        asyncImportExportTask.setListData(JsonUtils.toJsonString(listData));
        asyncImportExportTask.setJavaType(javaType.getName());
        asyncImportExportTask.setSheetName(sheetName);

        Long userId = getUserId();
        SysUser sysUser = sysUserService.selectUserById(userId);
        asyncImportExportTask.setCompanyId(sysUser.getDeptId());//用户部门ID
        asyncImportExportTask.setTaskStatus(1);
        asyncImportExportTask.setTaskType(2);
        asyncImportExportTask.setUserId(userId);//用户ID
        return baseMapper.insert(asyncImportExportTask) >0;
    }
    /**
     * 批量删除异步excel任务中心
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids) {

        return baseMapper.deleteBatchIds(ids) > 0;
    }
    private LambdaQueryWrapper<AsyncImportExportTask> buildQueryWrapper(AsyncImportExportTaskBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<AsyncImportExportTask> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getTaskName()), AsyncImportExportTask::getTaskName, bo.getTaskName());
        lqw.eq(bo.getCompanyId() != null, AsyncImportExportTask::getCompanyId, bo.getCompanyId());
        lqw.eq(true,AsyncImportExportTask::getUserId, getUserId());
//        lqw.eq(bo.getUserId() != null, AsyncImportExportTask::getUserId, bo.getUserId());
        lqw.eq(bo.getTaskStatus() != null, AsyncImportExportTask::getTaskStatus, bo.getTaskStatus());
        lqw.eq(bo.getCreatedTime() != null, AsyncImportExportTask::getCreatedTime, bo.getCreatedTime());
        lqw.eq(bo.getDealTime() != null, AsyncImportExportTask::getDealTime, bo.getDealTime());
        lqw.eq(bo.getFinishTime() != null, AsyncImportExportTask::getFinishTime, bo.getFinishTime());
        lqw.eq(StringUtils.isNotBlank(bo.getResult()), AsyncImportExportTask::getResult, bo.getResult());
        return lqw;
    }
}
